<template>
  <div class="">
    <el-form ref="mongodbOutput" :model="mongodbOutput" label-width="170px" size="mini">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="mongodbOutput.name"></el-input>
      </el-form-item>
      <el-tabs  v-model="tabsValue" type="border-card">
        <el-tab-pane label="配置连接" name="file">
          <el-form-item label="数据源:" prop="name">
            <el-popover
              ref="datasourceListPopover"
              placement="bottom-start"
              trigger="click"
              v-model="srcPopover">
              <table-tree ref="datasourceListTree"
                          @tableSelectHandler="tableSelectHandler"
                          style="height: 400px; overflow-y: auto"></table-tree>
              <el-input v-model="name" slot="reference"  placeholder="点击选择数据源"></el-input>
            </el-popover>
          </el-form-item>
          <el-form-item label="数据表:" prop="mongo_collection">
          <el-select v-model="mongodbOutput.mongo_collection" allow-create placeholder="请选择" filterable style="width: 90%">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="字段" name="fields">
          <template>
            <el-table :data="mongodbOutput.mongo_fields" border style="width: 100%;" :height="domHeight - 350 + 'px'" size="mini" @getStreamFieldOptions="getStreamFieldOptions" id="fields" ref="tableField">
              <el-table-column label="操作" width="80" :resizable=false>
                <template slot-scope="scope">
                  <div class="optionStyle">
                    <el-button
                      type="text"
                      @click="removeObj"
                      size="mini">移除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column property="incoming_field_name" label="名称">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.incoming_field_name" size="mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column property="mongo_doc_path" label="路径" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.mongo_doc_path" size="mini"></el-input>
                </template>
              </el-table-column>
              <!--<el-table-column property="use_incoming_field_name_as_mongo_field_name" label="使用字段名" >-->
                <!--<template slot-scope="scope">-->
                  <!--<el-input v-model="scope.row.use_incoming_field_name_as_mongo_field_name" size="mini"></el-input>-->
                <!--</template>-->
              <!--</el-table-column>-->
              <el-table-column property="use_incoming_field_name_as_mongo_field_name" label="使用字段名" >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.use_incoming_field_name_as_mongo_field_name"
                             placeholder="请选择字段" size="mini">
                    <el-option v-for="column in fieldTypeColumns"
                               :key="column.name"
                               :prop="column.code"
                               :label="column.name"
                               :value="column.code">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex">
              <el-button class="el-table-add-row" icon="el-icon-plus" @click="addObj">添加</el-button>
              <div style="width: 20px;"></div>
              <el-button class="el-table-add-row" icon="el-icon-thumb" @click="getField">获取字段</el-button>
              <div style="width: 20px;"></div>
              <el-button class="el-table-add-row" v-if="false">获取字段</el-button>
            </el-row>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="el-dialog__footer">
      <span  class="dialog-footer">
         <el-button
           icon="el-icon-back"
           @click="cancel">取消
            </el-button>
            <el-button
              type="primary" icon="el-icon-check"
              @click="handleSaveData()">确定
           </el-button>
      </span>
    </div>
  </div>
</template>
<script>
  /* eslint semi: ["error", "always"] */
  import API from '../../../../../api/index';
  // import TableFileds from '../../../table/table-fields.vue';
  import mxgraph from '../../../../../graph/VueMxGraphLoader';
  import tableTree from '../../../table/table-tree.vue';
  /* eslint-disable no-undef */
  /* eslint-disable no-new-object */
  /* eslint-disable no-new */
  /* eslint-disable new-cap */
  const {
    mxUtils,
    mxCodec
  } = mxgraph;
  export default {
    name: 'mongodbOutput',
    props: {
      name: String
    },
    components: {
      // 'u-table': TableFileds,
      tableTree
    },
    computed: {
      domHeight: {
        get () {
          return this.$store.state.common.documentClientHeight - this.$BODY_MARGIN - 60;
        }
      }
    },
    data () {
      return {
        srcPopover: false,
        graph: null,
        name: '',
        mongodbOutput: {
          host_id: '',
          name: '',
          mongo_host: '',
          mongo_port: '',
          mongo_auth_database: null,
          mongo_user: null,
          mongo_password: null,
          auth_mech: 'SCRAM-SHA-1',
          auth_kerberos: 'N',
          mongo_db: '',
          mongo_collection: '',
          batch_insert_size: '100',
          connect_timeout: null,
          socket_timeout: null,
          read_preference: 'primary',
          write_concern: null,
          w_timeout: null,
          journaled_writes: 'N',
          truncate: 'N',
          update: 'N',
          upsert: 'N',
          multi: 'N',
          modifier_update: 'N',
          use_all_replica_members: 'N',
          write_retries: '5',
          write_retry_delay: '10',
          mongo_fields: []
        },
        temp: {
          host_id: '',
          name: '',
          mongo_host: '',
          mongo_port: '',
          mongo_auth_database: null,
          mongo_user: null,
          mongo_password: null,
          auth_mech: 'SCRAM-SHA-1',
          auth_kerberos: 'N',
          mongo_db: '',
          mongo_collection: '',
          batch_insert_size: '100',
          connect_timeout: null,
          socket_timeout: null,
          read_preference: 'primary',
          write_concern: null,
          w_timeout: null,
          journaled_writes: 'N',
          truncate: 'N',
          update: 'N',
          upsert: 'N',
          multi: 'N',
          modifier_update: 'N',
          use_all_replica_members: 'N',
          write_retries: '5',
          write_retry_delay: '10',
          mongo_fields: []
        },
        tabsValue: 'file',
        fieldTypeColumns: [{code: 'Y', name: 'Y'},
          {code: 'N', name: 'N'}
        ]
      };
    },
    methods: {
      loadData (data) {
        console.log(data);
        if (data) {
          this.$forceUpdate();
          this.mongodbOutput = Object.assign({}, data);
          // 返回数据源id
          if (data.host_id) {
            const _this = this;
            window.setTimeout(function () {
              _this.$nextTick(() => {
                _this.name = _this.$refs.datasourceListTree.getName(data.host_id);
              });
            }, 1000);
          }
        }
      },
      /***
       * 表选中
       * @param data
       * @param node
       */
      tableSelectHandler (data, node) {
        this.mongodbOutput.mongo_collection = data.name; // 表名称赋值
        this.$http({
          url: this.$http.adornUrl(`/src/source/info/${node.parent.data.id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.mongodbOutput.host_id = data.entity.id;
            this.name = data.entity.name;
            this.mongodbOutput.mongo_host = data.entity.ip;
            this.mongodbOutput.mongo_port = data.entity.port;
            this.mongodbOutput.mongo_db = data.entity.dbName;
            this.mongodbOutput.auth_user = data.entity.userName;
            this.mongodbOutput.auth_password = data.entity.password;
            this.mongodbOutput.auth_mech = 'SCRAM-SHA-1';
          }
        });
        this.srcPopover = false;
      },
      // 保存表单数据
      handleSaveData () {
        console.log(this.mongodbOutput);
        this.$emit('savePluginData', this.mongodbOutput);
      },
      cancel () {
        this.$emit('cancel');
      },
      // 重置表单数据
      resetFormData (stepname) {
        this.$forceUpdate();
        this.$refs['mongodbOutput'].resetFields();
        this.mongodbOutput = JSON.parse(JSON.stringify(this.temp));
        this.mongodbOutput['name'] = stepname;
      },
      setGraph (val) {
        this.graph = val;
      },
      async getField () {
        let streamFields = await this.getStreamField();
        if (streamFields.data !== '') {
          streamFields.data = streamFields.data.map(v1 => {
            v1.incoming_field_name = v1.name;
            return v1;
          });
          this.$set(this.mongodbOutput, 'mongo_fields', streamFields.data);
        }
      },
      async getStreamField () {
        const value = await this.getXml();
        if (this.mongodbOutput.name) {
          return API.trans.inputFields(value, { stepName: this.mongodbOutput.name });
        }
      },
      getXml () {
        this.saveTempPluginData(this.mongodbOutput);
        const graph = this.graph;
        const enc = new mxCodec(mxUtils.createXmlDocument());
        const node = enc.encode(graph.getModel());
        const value = mxUtils.getPrettyXml(node);
        return value;
      },
      saveTempPluginData (formData) {
        this.$emit('saveTempPluginData', formData);
      },
      async getStreamFieldOptions () {
        const result = this.getStreamField();
        this.$refs['tableField'].setOptions(result);
      },
      removeObj (index) {
        this.mongodbOutput.mongo_fields.splice(index, 1);
      },
      addObj () {
        this.mongodbOutput.mongo_fields.push({});
        this.$nextTick(() => {
          let container = this.$el.querySelector('#fields > .el-table__body-wrapper');
          container.scrollTop = container.scrollHeight;
        });
      }
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .el-form-item {
    margin-bottom: 10px !important;
  }
  .upload-demo {
    display: inline;
  }
  .divBut {
    text-align: center;
    margin-top: 54px !important;
  }
  .el-dialog__footer {
    margin-top: 10px;
  }
  .button {
    width: 70px;
    height: 40px;
    display: inline-block;
    margin-left: 10px;
    margin-top: 5px;
  }
</style>
